<script setup>
import { ref, computed } from 'vue'
import { Download } from '@element-plus/icons-vue'
import { exportBusinessStatisticsReportService } from '@/api/report'
import TurnoverLineChart from './components/TurnoverLineChart.vue'
import MemberLineChart from './components/MemberLineChart.vue'
import BusinessLineChart from './components/BusinessLineChart.vue'
import ProjectBarChart from './components/ProjectBarChart.vue'
import EmployeeRankingTable from './components/EmployeeRankingTable.vue'
import MemberRankingTable from './components/MemberRankingTable.vue'
import { dayjs } from 'element-plus'
import { useUserStore } from '@/stores'

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const dateRanges = [
  { label: '昨日', type: 'yesterday' },
  { label: '近7日', type: '7days' },
  { label: '近30日', type: '30days' },
  { label: '本周', type: 'week' },
  { label: '本月', type: 'month' }
]

const selectedRange = ref('week')

// 计算日期范围
const dateRange = computed(() => {
  const now = dayjs()
  let begin, end
  switch (selectedRange.value) {
    case 'yesterday':
      begin = now.subtract(1, 'day').startOf('day')
      end = now.subtract(1, 'day').endOf('day')
      break
    case '7days':
      begin = now.subtract(7, 'day').startOf('day')
      end = now.endOf('day')
      break
    case '30days':
      begin = now.subtract(30, 'day').startOf('day')
      end = now.endOf('day')
      break
    case 'week':
      begin = now.startOf('week')
      end = now.endOf('week')
      break
    case 'month':
      begin = now.startOf('month')
      end = now.endOf('month')
      break
  }
  begin = begin.format('YYYY-MM-DD')
  end = end.format('YYYY-MM-DD')
  return { begin, end }
})

// 日期范围显示文本
const dateRangeText = computed(() => {
  let dateRangeText = '已选日期：'
  dateRangeText += `${dateRange.value.begin}`
  dateRangeText += ' 至 '
  dateRangeText += `${dateRange.value.end}`
  return dateRangeText
})

// 导出业务报表
const exportBusinessReport = async () => {
  const response = await exportBusinessStatisticsReportService()

  // 从响应头获取文件名（兼容不同格式）
  const contentDisposition = response.headers['content-disposition']
  let fileName = '业务统计报表.xlsx' // 默认文件名

  if (contentDisposition) {
    // 处理RFC5987编码格式（filename*=UTF-8''xxx）
    const utf8FilenameRegex = /filename\*=UTF-8''([^;]+)/i
    const utf8FilenameMatch = contentDisposition.match(utf8FilenameRegex)

    if (utf8FilenameMatch && utf8FilenameMatch[1]) {
      fileName = decodeURIComponent(utf8FilenameMatch[1])
    } else {
      // 处理普通格式（filename="xxx"或filename=xxx）
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i
      const filenameMatch = contentDisposition.match(filenameRegex)

      if (filenameMatch && filenameMatch[1]) {
        fileName = filenameMatch[1].replace(/['"]/g, '')
      }
    }
  }

  // 创建 Blob URL 并触发下载
  const blob = new Blob([response.data], {
    type: response.headers['content-type'] || 'application/octet-stream'
  })

  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName // 设置下载文件名
  document.body.appendChild(link)
  link.click()

  // 清理
  setTimeout(() => {
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }, 100)
}
</script>

<template>
  <el-container>
    <el-main>
      <!-- 新增的筛选行 -->
      <el-row>
        <el-col>
          <el-card class="section-card" shadow="hover">
            <el-button
              class="date-range-btn"
              :type="selectedRange === range.type ? 'primary' : ''"
              size="large"
              v-for="range in dateRanges"
              :key="range.type"
              @click="selectedRange = range.type"
            >
              {{ range.label }}
            </el-button>
            <span class="date-range">{{ dateRangeText }}</span>
            <el-button
              v-if="['管理员', '店长'].includes(userRole)"
              class="export-btn"
              type="primary"
              plain
              @click="exportBusinessReport"
            >
              <el-icon><Download /></el-icon>导出近30天业务统计报表
            </el-button>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- 营业额统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">营业额统计</div>
            <turnover-line-chart :date-range="dateRange" />
          </el-card>
        </el-col>
        <!-- 会员数量统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">会员数量统计</div>
            <member-line-chart :date-range="dateRange" />
          </el-card>
        </el-col>
      </el-row>

      <el-row class="mt-20" :gutter="20">
        <!-- 业务统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">业务统计</div>
            <business-line-chart :date-range="dateRange" />
          </el-card>
        </el-col>
        <!-- 服务项目排名统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">服务项目排名统计</div>
            <project-bar-chart :date-range="dateRange" />
          </el-card>
        </el-col>
      </el-row>

      <el-row class="mt-20" :gutter="20">
        <!-- 员工服务排名统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">员工服务排名统计</div>
            <employee-ranking-table :date-range="dateRange" />
          </el-card>
        </el-col>
        <!-- 会员消费排名统计 -->
        <el-col :span="12">
          <el-card class="section-card" shadow="hover">
            <div class="section-title">会员消费排名统计</div>
            <member-ranking-table :date-range="dateRange" />
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.el-main {
  padding: 0;
  overflow-x: hidden;
}

.date-range-btn {
  margin: 0;
  border-radius: 0;
}

.date-range {
  vertical-align: middle;
  margin-left: 20px;
  color: #333;
}

.export-btn {
  float: right;
}

.section-card {
  border-radius: 10px;
  margin-bottom: 10px;
}

.section-title {
  font-size: 18px;
  color: #000;
  font-weight: 700;
}

.data-card {
  border-radius: 10px;
  text-align: center;
  padding: 20px;
  transition: transform 0.2s;
  background-color: #f7fafc;

  &:hover {
    transform: translateY(-3px);
  }
}

.mt-20 {
  margin-top: 20px;
}
</style>
